<!--
 - Author : wang885298.
 - Date   : 2018/9/11.
 - File   : roadData.
 -->

<template>
  <div class="content">
    <div class="block">
      <!--功能栏-->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="搜索路名"
            v-model="cn"
            @input="searchRoad">
            <i slot="suffix" class="el-input__icon el-icon-search"></i>
          </el-input>
        </el-col>
        <el-col :span="16" style="text-align: right">
          <el-button type="primary" @click="openBatchRoad "><i
            class="el-icon-circle-plus-outline el-icon--left"></i>批量添加道路
          </el-button>
          <el-button type="primary" @click="addOrEdit()">
            <i class="el-icon-circle-plus-outline el-icon--left"></i>添加道路
          </el-button>
        </el-col>
      </el-row>
      <!--名称栏-->
      <div class="title">全部道路列表</div>
      <!--列表-->
      <el-row class="border-top">
        <el-table
          ref="multipleTable"
          :data="roadList"
          tooltip-effect="dark"
          style="width: 100%"
          :row-class-name="tableRowClassName"
          @selection-change="handleSelectionChange">
          <el-table-column
            type="selection"
            width="55">
          </el-table-column>
          <el-table-column
            label="道路名称"
            show-overflow-tooltip>
            <template slot-scope="scope">{{ scope.row.roadName }}</template>
          </el-table-column>
          <el-table-column
            prop="streetName"
            label="所属乡/镇/街道"
            show-overflow-tooltip>
          </el-table-column>
          <el-table-column
            prop="districtName"
            label="所属区/县"
            show-overflow-tooltip>
          </el-table-column>
          <el-table-column
            label="所属市"
            show-overflow-tooltip>
            <template slot-scope="scope">{{ scope.row.cityName }}</template>
          </el-table-column>
          <el-table-column
            label="所属省"
            show-overflow-tooltip>
            <template slot-scope="scope">{{ scope.row.provinceName }}</template>
          </el-table-column>
          <el-table-column
            label="创建人"
            show-overflow-tooltip>
            <template slot-scope="scope">{{ scope.row.creatorName }}</template>
          </el-table-column>
          <el-table-column
            label="创建时间"
            show-overflow-tooltip>
            <template slot-scope="scope">{{ scope.row.createTime }}</template>
          </el-table-column>
          <el-table-column label="操作" align="right">
            <template slot-scope="scope">
              <el-button
                type="text"
                size="small"
                @click="addOrEdit(scope)">编辑
              </el-button>
              <el-button
                type="text"
                size="small"
                @click="singleDelete(scope.$index, scope.row)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-row :gutter="20" style="margin-top: 20px">
          <el-col :span="4">
            <el-button type="danger" @click="delSelect()" plain><i
              class="el-icon-delete el-icon--left"></i>删除
            </el-button>
          </el-col>
          <el-col :span="16" style="text-align: center">
            <el-button type="primary" round @click="loadMore()" v-show="showLoadMore">点击加载更多...</el-button>
            <el-button type="info" round v-show="!showLoadMore && roadList.length>0" disabled>没有更多数据了</el-button>
          </el-col>
          <el-col :span="4"></el-col>
        </el-row>
      </el-row>
    </div>
    <!--添加和编辑道路dialog-->
    <el-dialog :title="boxTitle" :visible.sync="addRoadVisible">
      <el-form :model="form" label-position="left">
        <el-form-item label="所属省" :label-width="formLabelWidth">
          <el-select
            v-model="form.provinceName"
            filterable
            remote
            clearable
            placeholder="请选择/输入所属省"
            size="medium"
            @change="change('1')"
            @focus="focus('1')"
            :remote-method="selectProvince">
            <el-option
              v-for="item in form.provinceList"
              :key="item.provinceId"
              :label="item.cn"
              :value="item.provinceId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属市" :label-width="formLabelWidth">
          <el-select
            v-model="form.cityName"
            filterable
            remote
            clearable
            :remote-method="selectCity"
            placeholder="请选择/输入所属市"
            @change="change('2')"
            @focus="focus('2')">
            <el-option
              v-for="item in form.cityList"
              :key="item.cityId"
              :label="item.cn"
              :value="item.cityId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属区/县" :label-width="formLabelWidth">
          <el-select
            v-model="form.districtName"
            filterable
            remote
            clearable
            placeholder="请选择/输入所属区/县"
            :remote-method="selectDistrict"
            @change="change('3')"
            @focus="focus('3')">
            <el-option
              v-for="item in form.districtsList"
              :key="item.districtId"
              :label="item.cn"
              :value="item.districtId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所属乡/镇/街道" :label-width="formLabelWidth">
          <el-select
            v-model="form.streetName"
            filterable
            remote
            clearable
            placeholder="请选择/输入所属乡/镇/街道"
            :remote-method="selectStreet"
            @change="change('4')"
            @focus="focus('4')">
            <el-option
              v-for="item in form.streetList"
              :key="item.streetId"
              :label="item.cn"
              :value="item.streetId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="道路名称" :label-width="formLabelWidth">
          <el-input v-model="form.roadName"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addRoadVisible = false">取 消</el-button>
        <el-button type="primary" @click="addOrEditRoad">确 定</el-button>
      </div>
    </el-dialog>
    <!--批量添加道路dialog-->
    <el-dialog title="批量添加" :visible.sync="addBatchRoadVisible">
      <div v-show="file.completeMatch===null">
        <el-row :gutter="20">
          <el-col :span="20"><input type="file" id="file" accept="application/vnd.ms-excel" @change="upload"/></el-col>
          <el-col :span="4">
            <a href="../../static/source/road.xlsx" download="道路导入模板.xlsx">下载模板</a>
          </el-col>
        </el-row>
        <div class="accept">提示：上传文件只支持Excel文档格式</div>
      </div>
      <div>
        <el-row :gutter="20" v-show="file.completeMatch!==null">
          <el-col :span="16">{{fileName}}</el-col>
          <el-col :span="8">
            <div class="checkOver">{{tips}}</div>
          </el-col>
        </el-row>
        <div v-show="file.completeMatch==='T' && file.correctData.length>0">所有记录符合上传条件，等待添加！</div>
        <div class="errorBg error" v-show="file.completeMatch==='T' && file.correctData.length===0">文档内数据不能为空！请添加后再上传
        </div>
        <div :key="index" v-for="(item, index) in file.errorData" v-show="file.completeMatch==='F'">
          <div class="errorBg" v-show="item.number.length>0">
            第<span :key="key" class="checkOver lineSpan" v-for="(n, key) in item.number">{{n}}</span> 行记录添加失败，失败原因为:<span
            class="checkOver">
            {{item.error | fileErrorStatue}}</span>
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <div v-show="file.completeMatch===null">
          <el-button @click="addBatchRoadVisible = false">取 消</el-button>
          <el-button type="primary" @click="checkFile">开始校验</el-button>
        </div>
        <div v-show="file.completeMatch==='T' && file.correctData.length>0">
          <el-button @click="addBatchRoadVisible = false">取 消</el-button>
          <el-button type="primary" @click="batchAdd">开始添加</el-button>
        </div>
        <div v-show="file.completeMatch==='F' || (file.completeMatch==='T' && file.correctData.length===0)">
          <el-button type="primary" @click="addBatchRoadVisible = false">确定</el-button>
        </div>
        <div v-show="file.completeMatch==='O'">
          <el-button type="primary" @click="ok">确定</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        currentPage: 1,
        pageSize: 10,
        roadList: [],
        showLoadMore: false,
        cn: '',
        multipleSelection: [],
        addRoadVisible: false,
        formLabelWidth: '120px',
        boxTitle: '新增道路',
        form: {
          provinceList: [],
          provinceId: '',
          provinceName: '',
          cityList: [],
          cityId: '',
          cityName: '',
          districtsList: [],
          districtId: '',
          districtName: '',
          streetList: [],
          streetId: '',
          streetName: '',
          roadName: '',
          roadId: ''
        },
        addBatchRoadVisible: false,
        editOrAdd: 'add',
        file: {
          completeMatch: null,
          correctData: [],
          errorData: []
        },
        fileParam: null,
        fileName: '',
        tips: '校验完毕！'
      }
    },
    methods: {
      init() {
        this.getRoadList() // 获取街道列表
      },
      /**
       * 关闭或取消上传文件弹窗
       * @returns {*}
       */
      openBatchRoad() {
        this.addBatchRoadVisible = true
        this.file = {
          completeMatch: null,
          correctData: [],
          errorData: []
        }
        this.fileParam = null
        this.fileName = ''
        let file = document.getElementById('file')
        if (file) {
          file.value = ''
        }
      },
      /**
       * 上传文件
       * @returns {*}
       */
      upload(e) {
        let str = e.target.files[0].name
        let tmp = str.split('.')[1]
        if (tmp === 'xls' || tmp === 'xlsx') {
          this.fileParam = new FormData()
          this.fileParam.append('ct', '{}')
          this.fileParam.append('file', e.target.files[0])
          this.fileName = e.target.files[0].name
        } else {
          this.$notify.error({
            title: '文件格式错误',
            message: '请选择excel文件'
          })
          let file = document.getElementById('file')
          file.value = ''
        }
      },
      /**
       * 后台校验文件
       * @returns {*}
       */
      checkFile() {
        if (this.fileParam) {
          this.$request.roadBatchCheck(this.fileParam).then((response) => {
            this.file = response
            console.log(response, 'response')
          }).catch((e) => {
            console.error(e)
          })
        } else {
          this.$notify.error({
            title: '错误',
            message: '请先选择文件，再进行校验'
          })
        }
      },
      /**
       * 批量添加道路数据
       * @returns {*}
       */
      batchAdd() {
        let param = {
          correctData: this.file.correctData
        }
        this.$request.roadBatchAdd(param).then((response) => {
          console.log('添加完成', response)
          this.tips = '添加完成！'
          this.file.completeMatch = 'O'
        }).catch((e) => {
          console.error(e)
          this.tips = '添加失败！' + e
        })
      },
      /**
       * 初始化获取街道列表
       * @returns {*}
       */
      ok() {
        this.addBatchRoadVisible = false
        this.getRoadList()
      },
      /**
       * 初始化获取街道列表
       * @returns {*}
       */
      getRoadList() {
        this.roadList = []
        this.currentPage = 1
        this.getRoad(this.pageSize, this.currentPage, this.cn)
      },
      /**
       * 获取街道列表
       * @param pageSize
       * @param page
       * @param cn 道路名
       * @returns {*}
       */
      getRoad(pageSize, page, cn) {
        let params
        if (cn === '') {
          params = {
            _pageSize: pageSize,
            _page: page
          }
        } else {
          params = {
            _pageSize: pageSize,
            _page: page,
            cn: cn
          }
        }
        this.$request.roadListGet(params).then((response) => {
          this.roadList = this.roadList.concat(response)
          this.showLoadMore = response.length > (this.pageSize - 1)
        }).catch((e) => {
          console.error(e)
        })
      },
      /**
       * 点击加载更多
       */
      loadMore() {
        this.getRoad(this.pageSize, ++this.currentPage, this.cn)
      },
      /**
       * 搜索道路
       */
      searchRoad() {
        this.roadList = []
        this.currentPage = 1
        this.$utils.throttle(this.getRoad(this.pageSize, this.currentPage, this.cn), 300)
      },
      /**
       * select聚焦
       * @param type 选择的所属类型
       * @returns {*}
       */
      focus(type) {
        let pcn = (this.form.provinceName !== '') ? this.form.provinceName : ''
        let provinceId, cn, cityId, dCn, districtId, sCn
        if (this.editOrAdd === 'edit') {
          provinceId = this.form.provinceId
          cn = (this.form.cityName !== '') ? this.form.cityName : ''
          cityId = this.form.cityId
          dCn = (this.form.cityName !== '') ? this.form.districtName : ''
          districtId = this.form.districtId
          sCn = (this.form.districtName !== '') ? this.form.streetName : ''
        } else {
          provinceId = (this.form.provinceId !== '') ? this.form.provinceId : ''
          cn = (this.form.cityName !== '') ? this.form.cityName : ''
          cityId = (this.form.provinceId !== '') ? this.form.cityId : ''
          dCn = (this.form.cityName !== '') ? this.form.districtName : ''
          districtId = (this.form.cityId !== '') ? this.form.districtId : ''
          sCn = (this.form.districtName !== '') ? this.form.streetName : ''
        }
        switch (type) {
          case '1':
            this.getProvinceList(pcn)
            break
          case '2':
            this.getCityList(provinceId, cn)
            break
          case '3':
            this.getDistrict(cityId, dCn)
            break
          case '4':
            this.getStreet(districtId, sCn)
            break
        }
      },
      /**
       * select改变选项
       * @param type 选择的所属类型
       * @returns {*}
       */
      change(type) {
        switch (type) {
          case '1':
            this.form.provinceId = this.form.provinceName
            this.form.cityName = null
            this.form.districtName = null
            this.form.streetName = null
            this.form.cityId = null
            this.form.districtId = null
            this.form.streetId = null
            break
          case '2':
            this.form.cityId = this.form.cityName
            this.form.districtName = null
            this.form.streetName = null
            this.form.districtId = null
            this.form.streetId = null
            break
          case '3':
            this.form.districtId = this.form.districtName
            this.form.streetName = null
            this.form.streetId = null
            break
          case '4':
            this.form.streetId = this.form.streetName
            break
        }
      },
      /**
       * 获取中国省/直辖市/特区/州元数据列表
       * @param cn 中国省/直辖市/特区/州
       * @returns {*}
       */
      getProvinceList(cn) {
        this.form.provinceList = []
        let params
        if (cn === '') {
          params = {}
        } else {
          params = {
            cn: cn
          }
        }
        this.$request.provinceListGet(params).then((response) => {
          if (!this.$utils.isEmptyObject(response)) {
            this.form.provinceList = response
          }
        }).catch((e) => {
          console.error(e)
        })
      },
      /**
       * 根据关键字搜索省份
       * @param query 关键字
       * @returns {*}
       */
      selectProvince(query) {
        if (query !== null) {
          this.getProvinceList(query)
        } else {
          this.getProvinceList('')
        }
      },
      /**
       * 获取城市元数据列表
       * @param provinceId 省份id
       * @param cn 关键字
       * @returns {*}
       */
      getCityList(provinceId, cn) {
        this.form.cityList = []
        let params
        if (cn === '') {
          params = {
            provinceId: provinceId
          }
        } else {
          params = {
            provinceId: provinceId,
            cn: cn
          }
        }
        if (this.$utils.isEmptyObject(params.provinceId)) {
          this.$notify.error({
            title: '错误',
            message: '请选择所属省'
          })
        } else {
          this.$request.cityListGet(params).then((response) => {
            this.form.cityList = response
          }).catch((e) => {
            console.error(e)
          })
        }
      },
      /**
       * 根据关键字搜索市区
       * @param query 关键字
       * @returns {*}
       */
      selectCity(query) {
        let provinceId = this.form.provinceId
        if (!this.$utils.isEmptyObject(query)) {
          this.getCityList(provinceId, query)
        } else {
          this.getCityList(provinceId, '')
        }
      },
      /**
       * 获取区县元数据列表
       * @param cityId 城市id
       * @param cn 关键字
       * @returns {*}
       */
      getDistrict(cityId, cn) {
        this.form.districtsList = []
        let params
        if (cn === '') {
          params = {
            cityId: cityId
          }
        } else {
          params = {
            cityId: cityId,
            cn: cn
          }
        }
        if (this.$utils.isEmptyObject(params.cityId)) {
          this.$notify.error({
            title: '错误',
            message: '请选输入或选择所属省份、城市'
          })
        } else {
          this.$request.districtListGet(params).then((response) => {
            this.form.districtsList = response
          }).catch((e) => {
            console.error(e)
          })
        }
      },
      /**
       * 根据关键字搜索区县
       * @param query 关键字
       * @returns {*}
       */
      selectDistrict(query) {
        let cityId = this.form.cityId
        if (!this.$utils.isEmptyObject(query)) {
          this.getDistrict(cityId, query)
        } else {
          this.getDistrict(cityId, '')
        }
      },
      /**
       * 获取县街道元数据列表
       * @param districtId 城市id
       * @param cn 关键字
       * @returns {*}
       */
      getStreet(districtId, cn) {
        this.form.streetList = []
        let params
        if (cn === '') {
          params = {
            districtId: districtId
          }
        } else {
          params = {
            districtId: districtId,
            cn: cn
          }
        }
        if (this.$utils.isEmptyObject(params.districtId)) {
          this.$notify.error({
            title: '错误',
            message: '请输入或选择所属省份、城市、区县'
          })
        } else {
          this.$request.streetListGet(params).then((response) => {
            this.form.streetList = response
          }).catch((e) => {
            console.error(e)
          })
        }
      },
      /**
       * 根据关键字搜索区县
       * @param query 关键字
       * @returns {*}
       */
      selectStreet(query) {
        let districtId = this.form.districtId
        if (!this.$utils.isEmptyObject(query)) {
          this.getStreet(districtId, query)
        } else {
          this.getStreet(districtId, '')
        }
      },
      /**
       * 全选、反选功能
       * @param val
       * @returns {*}
       */
      handleSelectionChange(val) {
        this.multipleSelection = val
      },
      /**
       * 编辑和单条添加道路弹窗功能
       * @param item
       * @returns {*}
       */
      addOrEdit(item) {
        this.addRoadVisible = true
        if (item) {
          this.editOrAdd = 'edit'
          this.boxTitle = '编辑道路'
          this.form.provinceName = item.row.provinceName
          this.form.cityName = item.row.cityName
          this.form.districtName = item.row.districtName
          this.form.streetName = item.row.streetName
          this.form.roadName = item.row.roadName
          this.form.provinceId = item.row.provinceId
          this.form.cityId = item.row.cityId
          this.form.districtId = item.row.districtId
          this.form.streetId = item.row.streetId
          this.form.roadId = item.row.roadId
        } else {
          let form = {
            provinceList: [],
            provinceId: '',
            provinceName: '',
            cityList: [],
            cityId: '',
            cityName: '',
            districtsList: [],
            districtId: '',
            districtName: '',
            streetList: [],
            streetId: '',
            streetName: '',
            roadName: '',
            roadId: ''
          }
          this.editOrAdd = 'add'
          this.boxTitle = '新增道路'
          this.form = form
        }
      },
      /**
       * 编辑道路或单条添加道路功能
       * @returns {*}
       */
      addOrEditRoad() {
        if (this.editOrAdd === 'add') { // 添加道路操作
          let params = {
            streetId: this.form.streetId,
            cn: this.form.roadName
          }
          this.$request.roadAdd(params).then((response) => {
            console.log('response', response)
            this.$message({
              type: 'success',
              message: '添加成功!'
            })
            this.getRoadList()
            this.addRoadVisible = false
          }).catch((e) => {
            console.error(e)
          })
        } else { // 编辑道路操作
          let params = {
            streetId: this.form.streetId,
            cn: this.form.roadName,
            roadId: this.form.roadId
          }
          this.$request.roadUpdate(params).then((response) => {
            console.log('response', response)
            this.$message({
              type: 'success',
              message: '修改成功!'
            })
            this.getRoadList()
            this.addRoadVisible = false
          }).catch((e) => {
            console.error(e)
          })
        }
      },
      /**
       * 删除单条道路信息功能
       * @param row 当前选中项数据
       * @param index
       * @returns {*}
       */
      singleDelete(index, row) {
        this.$confirm('是否删除“' + row.roadName + '”这条道路?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let params = {
            roadId: row.roadId
          }
          this.$request.roadDel(params).then((response) => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.getRoadList()
          }).catch((e) => {
            console.error(e)
          })
        }).catch(() => {
        })
      },
      /**
       * 表格列表间隔颜色功能
       * @param row
       * @param rowIndex
       * @returns {*}
       */
      /**
       * 批量删除功能
       * @returns {*}
       */
      delSelect() {
        if (this.multipleSelection.length > 0) {
          let roadIds = []
          this.multipleSelection.forEach(function (value, index, list) {
            roadIds.push(list[index].roadId)
          })
          this.$confirm('是否删除选中项?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            let params = {
              roadIds: roadIds
            }
            this.$request.roadBatchDel(params).then((response) => {
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
              this.roadList = []
              this.currentPage = 1
              this.getRoadList()
            }).catch((e) => {
              console.error(e)
            })
          }).catch(() => {
          })
        } else {
          this.$message({
            type: 'warning',
            message: '请勾选要删除的项'
          })
        }
      },
      tableRowClassName({row, rowIndex}) {
        if (rowIndex % 2 === 0) {
          return 'success-row'
        } else {
          return ''
        }
      }
    },
    mounted() {
      this.init()
    }
  }
</script>

<style>
  .el-dialog {
    max-width: 650px;
  }

  .error {
    color: red;
  }

  .checkOver {
    color: red;
    text-align: right;
  }

  .errorBg {
    background: rgba(189, 189, 184, 0.12);
    padding: 10px 15px;
    margin-bottom: 2px;
  }

  .errorBg > .lineSpan:after {
    content: '、';
  }

  .errorBg > span:last-child {
    content: '*';
  }

  .accept {
    background: rgba(189, 189, 184, 0.12);
    padding: 10px 15px;
    color: #409eff;
  }
</style>
